<template>
	<dt-main-body v-model="labelPosition">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>投稿管理</el-breadcrumb-item>
				<el-breadcrumb-item>编辑投稿</el-breadcrumb-item>
			</el-breadcrumb>
		</div>

		<div class="content-box">
			<el-form ref="editForm" :model="model" :rules="rules" :label-position="labelPosition" label-width="120px">
				<el-tabs v-model="activeName" type="card">
					<el-tab-pane label="基本信息" name="info">
						<div class="tab-content">
							<el-form-item prop="channelId" label="所属频道">
								<el-select v-model="model.channelId" :disabled="model.id>0" placeholder="请选择..." @change="handleChannelChange">
									<el-option v-for="item in channelList"
										:key="item.id"
										:label="item.title"
										:value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="title" label="文章标题">
								<el-input v-model="model.title" placeholder="必填，512字符内"></el-input>
							</el-form-item>
							<el-form-item prop="source" label="文章来源">
								<el-input v-model="model.source" placeholder="必填，128字符内"></el-input>
							</el-form-item>
							<el-form-item prop="author" label="文章作者">
								<el-input v-model="model.author" placeholder="必填，128字符内"></el-input>
							</el-form-item>
							<el-form-item prop="imgUrl" label="封面图片">
								<dt-upload-text v-model="model.imgUrl" placeholder="请上传封面图片" :size="sysconfig.imgSize"></dt-upload-text>
							</el-form-item>
							<el-form-item v-show="channelModel.isAlbum==1" label="相册上传">
								<dt-upload-album v-model="form.albumList"></dt-upload-album>
							</el-form-item>
							<el-form-item v-show="channelModel.isAttach==1" label="附件上传">
								<dt-upload-attach v-model="form.attachList" :size="sysconfig.attachSize" :exts="sysconfig.fileExtension"></dt-upload-attach>
							</el-form-item>
							<el-form-item prop="content" label="内容介绍">
								<dt-editor v-model="model.content" placeholder="请输入内容介绍"></dt-editor>
							</el-form-item>
							<el-form-item label="状态">
								<el-radio-group v-model="model.status" @@change="handleChangeStatus">
									<el-radio-button label="0">待审</el-radio-button>
									<el-radio-button label="1">通过</el-radio-button>
									<el-radio-button label="2">返回</el-radio-button>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="创建时间" v-if="model.id>0">
								{{model.userName}} {{model.addTime}}
							</el-form-item>
							<el-form-item label="最后更新" v-if="model.id>0&&model.updateTime">
								{{model.updateBy}} {{model.updateTime}}
							</el-form-item>
							<el-form-item v-if="status!=1&&model.status==1&&model.id>0" prop="categorys" label="所属父类别">
								<el-dropdown split-button class="dropdown-tree">
									<input type="text" v-model="model.categorys" style="display:none;" />
									<div class="dropdown-multiple-tree-lable">{{dropdownMultipleTree.dropdownLable}}</div>
									<el-dropdown-menu slot="dropdown">
										<el-tree :data="treeCategoryList"
											ref="categoryTree"
											:default-expand-all="true"
											:expand-on-click-node="false"
											@@check="handleDropdownMultipleTreeCheck"
											node-key="id"
											show-checkbox
											:props="defaultProps">
										</el-tree>
									</el-dropdown-menu>
								</el-dropdown>
							</el-form-item>
						</div>
					</el-tab-pane>
					<template v-if="model.fields.length>0">
						<el-tab-pane label="扩展内容" name="fields">
							<div class="tab-content">
								<template v-for="(field,index) in model.fields">
									<!--单行文本框-->
									<el-form-item v-if="field.controlType=='input'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-input v-if="field.isPassword==0" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
										<el-input v-else v-model="field.fieldValue" :placeholder="field.validTipMsg" show-password></el-input>
									</el-form-item>
									<!--多行文本框-->
									<el-form-item v-else-if="field.controlType=='textarea'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-input type="textarea" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
									</el-form-item>
									<!--编辑器-->
									<el-form-item v-else-if="field.controlType=='editor'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<div style="min-height:230px;">
											<dt-editor v-if="field.editorType==0" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
											<dt-editor mini v-if="field.editorType==1" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
										</div>
									</el-form-item>
									<!--图片上传-->
									<el-form-item v-else-if="field.controlType=='images'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<dt-upload-text v-model="field.fieldValue"
											:placeholder="field.validTipMsg"
											exts="jpg,jpeg,png,gif"
											:size="sysconfig.imgSize"
											action="/upload">
										</dt-upload-text>
									</el-form-item>
									<!--视频上传-->
									<el-form-item v-else-if="field.controlType=='video'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<dt-upload-text v-model="field.fieldValue"
											:placeholder="field.validTipMsg"
											:exts="sysconfig.videoExtension"
											:size="sysconfig.videoSize"
											action="/upload">
										</dt-upload-text>
									</el-form-item>
									<!--日期时间-->
									<el-form-item v-else-if="field.controlType=='datetime'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-date-picker v-model="field.fieldValue" value-format="yyyy-MM-dd hh:mm:ss" :placeholder="field.validTipMsg" type="datetime">
										</el-date-picker>
									</el-form-item>
									<!--多项单选-->
									<el-form-item v-else-if="field.controlType=='radio'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-radio-group v-model="field.fieldValue">
											<el-radio v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-radio>
										</el-radio-group>
									</el-form-item>
									<!--多项多选-->
									<el-form-item v-else-if="field.controlType=='checkbox'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
										<el-checkbox-group v-model="field.fieldValue">
											<el-checkbox v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-checkbox>
										</el-checkbox-group>
									</el-form-item>
								</template>
							</div>
						</el-tab-pane>
					</template>
				</el-tabs>
			</el-form>
		</div>
		
		<div class="footer-box">
			<div class="footer-btn">
				<el-button type="primary" @click="submitForm">确认保存</el-button>
				<el-button plain @click="$common.back()">返回上一页</el-button>
			</div>
		</div>
	</dt-main-body>
</template>

<script>
	import DtUploadText from '../../../components/DtUploadText.vue'
	import DtUploadAlbum from '../../../components/DtUploadAlbum.vue'
	import DtUploadAttach from '../../../components/DtUploadAttach.vue'
	import DtEditor from '../../../components/DtEditor.vue'
	
	export default {
		components: {
			DtUploadText,
			DtUploadAlbum,
			DtUploadAttach,
			DtEditor
		},
		props: {
			channelId: 0,
			id: 0
		},
		data() {
			return {
				activeName: 'info', //当前选项卡
				labelPosition: 'right', //表单对齐方式
				form: {
					albumList: [],//相册列表,保存取值
					attachList: [],
				},
				channelList: [],//频道列表
				channelModel: {},
				sysconfig: {},
				fieldRules: {},
				status: 0,
				treeCategoryList: [],
				dropdownMultipleTree: {
					dropdownLable: '请选择栏目类别',
				},
				defaultProps: {
					value: 'id',
					label: 'title',
					children: 'children',
					multiple: true,
					checkStrictly: true,
				},
				model: {
					id: 0,
					channelId: null,
					title: null,
					source: null,
					author: null,
					imgUrl: null,
					fieldMeta: null,
					albumMeta: null,
					attachMeta: null,
					content: null,
					userId: 0,
					userName: null,
					addTime: null,
					updateBy: null,
					updateTime: null,
					status: 0,
					fields: [],
					categorys: [],
					albums: [],
					attachs: [],
				},
				rules: {
					title: [
						{ required: true, message: '标题不可为空', trigger: 'blur' },
						{ max: 512, message: '标题不可超出512字符', trigger: 'blur' }
					],
					source: [
						{ max: 128, message: '来源不可超出128字符', trigger: 'blur' }
					],
					author: [
						{ max: 128, message: '作者不可超出128字符', trigger: 'blur' }
					],
					imgUrl: [
						{ max: 512, message: '图片地址不可超出512字符', trigger: 'blur' }
					],
					categorys: [
						{ type: 'array', required: true, message: '请选择栏目类别', trigger: 'blur' },
					],
				},
			}
		},
		methods: {
			//初始化数据
			async initData() {
				let _this = this; //当前页面
				const loading = _this.$loading();
				//获取系统信息
				await _this.$api.request({
					url: `/admin/setting/sysconfig`,
					success(res) {
						_this.sysconfig = res.data;
					}
				});
				//频道信息
				await _this.$api.request({
					url: `/admin/channel/${_this.channelId}`,
					success(res) {
						_this.channelModel = res.data;
					}
				});
				//获取频道列表
				await _this.$api.request({
					url: `/admin/channel/view/0?siteId=${_this.channelModel.siteId}`,
					success(res) {
						_this.channelList = res.data;
					}
				});
				//获取分类列表
				await _this.$api.request({
					url: `/admin/article/category/${_this.channelId}`,
					success(res) {
						_this.treeCategoryList = res.data;
					}
				});
				if (_this.id) {
					_this.$api.request({
						url: `/admin/article/contribute/${_this.channelId}/${_this.id}/view`,
						success(res) {
							//赋值给model
							Object.keys(_this.model).forEach(key => {
								_this.model[key] = res.data[key];
							});
							//赋值扩展字段
							_this.status = _this.model.status;
							//相册赋值
							if (_this.model.albums) {
								_this.model.albums.map(function (item) {
									item.url = item.thumbPath;
									item.id = 0;
									_this.form.albumList.push(item);
								})
							}
							//附件赋值
							if (_this.model.attachs) {
								_this.model.attachs.map(function (item) {
									item.fileName = item.fileName;
									item.articleId = item.articleId;
									item.filePath = item.filePath;
									item.fileSize = item.fileSize;
									item.fileExt = item.fileExt;
									item.downCount = item.downCount;
									item.id = 0;
									_this.form.attachList.push(item);
								})
							}
						}
					});
				} else {
					//赋值扩展字段
					_this.model.fields = _this.channelModel.fields;
				}
				//获得频道扩展字段
				_this.initFields();
				loading.close();
			},
			//提交表单
			submitForm() {
				let _this = this; //当前页面
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['editForm'].validate((valid) => {
						if (valid) resolve();
					});
				});
				Promise.all([f1]).then(() => {
					let model = JSON.parse(JSON.stringify(_this.model));
					//处理扩展字段
					model.fields.forEach(function (val, index) {
						if (Array.isArray(val.fieldValue)) {
							val.fieldValue = val.fieldValue.join(',');
						}
					});
					//格式化相册数据去除没有上传成功的数据
					_this.formatAlbum();
					//格式化附件数据去除没有上传成功的数据
					_this.formatAttach();
					//相册取值
					let albumList = [];
					_this.form.albumList.map(function (item) {
						albumList.push({
							id: 0,
							articleId: 0,
							thumbPath: item.thumbPath,
							originalPath: item.originalPath,
							remark: item.remark
						});
					});
					model.albums = albumList;
					//附件取值
					let attachList = [];
					_this.form.attachList.map(function (item) {

						attachList.push({
							id: 0,
							fileName: item.fileName,
							articleId: 0,
							filePath: item.filePath,
							fileSize: item.fileSize,
							fileExt: item.fileExt,
							downCount: item.downCount,
						});
					});
					model.attachs = attachList;
					//提交表单,Id大于0则修改，否则添加
					if (_this.model.id > 0) {
						_this.$api.request({
							method: 'put',
							url: `/admin/article/contribute/${_this.model.channelId}/${_this.model.id}`,
							data: model,
							loading: true,
							successMsg: '修改成功',
							success(res) {
								//可跳转加列表页
								_this.$common.linkUrl(`/article/contribute/list/${_this.channelId}`);
							}
						});
					} else {
						_this.$api.request({
							method: 'post',
							url: `/admin/article/contribute/${_this.model.channelId}`,
							data: model,
							loading: true,
							successMsg: '新增成功',
							success(res) {
								//重置表单
								_this.$refs['editForm'].resetFields();
								_this.form.albumList = [];
								_this.form.attachList = [];
								_this.model.albums = [];
								_this.model.attachs = [];
								_this.model.albumMeta = '';
								_this.model.attachMeta = '';
								_this.model.fieldMeta = '';
							}
						});
					}
				})
			},
			//频道变化
			handleChannelChange(val) {
				let _this = this;
				_this.getChannelModel(val);
			},
			//获得频道信息
			getChannelModel(channelId) {
				let _this = this;
				_this.$api.request({
					url: `/admin/channel/${channelId}`,
					loading: false,
					success(res) {
						_this.channelModel = res.data;
						_this.model.fields = _this.channelModel.fields;
						//获得频道扩展字段
						_this.initFields();

					}
				});
			},
			//初始化扩展字段
			initFields() {
				let _this = this;
				//重置验证规则
				_this.fieldRules = {};
				//重置表单
				_this.channelModel.fields.forEach(function (val, i) {
					//编辑的时候触发
					if (_this.model.id>0) {
						//获得扩展字段值
						let obj = getFieldsValue(val.name);
						//构建Fields属性
						val.fieldName = val.name;
						val.fieldId = obj.id;
						//如果值存在，将值替换默认值
						if (obj.value) {
							//如果是数组
							if (Array.isArray(val.fieldValue)) {
								val.fieldValue = obj.value.split(',');
							} else {
								val.fieldValue = obj.value;
							}

						} else {
							if (Array.isArray(val.fieldValue)) {
								val.fieldValue = [];
							} else {
								val.fieldValue = '';
							}

						}
					} else {
						//构建Fields属性
						val.fieldName = val.name;
						val.fieldId = val.id;
					}
					//生成验证规则
					getRules(val);
				});
				_this.model.fields = _this.channelModel.fields;
				function getFieldsValue(name) {
					let obj = { value: '', id: 0 };
					let fields = JSON.parse(_this.model.fieldMeta)
					if (fields.length > 0) {
						fields.forEach(function (val, index) {
							if (val.fieldName == name) {
								obj = { value: val.fieldValue, id: val.fieldId };
							}
						});
					}
					return obj;
				}
				//生成验证规则
				function getRules(obj) {
					let item = [];
					//blur验证的控件
					if (obj.controlType == 'input' ||
						obj.controlType == 'textarea' ||
						obj.controlType == 'editor' ||
						obj.controlType == 'images' ||
						obj.controlType == 'video' ||
						obj.controlType == 'datetime'
					) {
						//必填项
						if (obj.isRequired == 1) {
							let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'blur' };
							item.push(eleRule);
						}
						//检查正则是否为null
						if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
							//不为空，将字符串转成正则表达式
							let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'blur' }
							item.push(eleRule);
						}

					} else if (obj.controlType == 'radio' ||
						obj.controlType == 'checkbox') {
						//change验证的控件
						//必填项
						if (obj.isRequired == 1) {
							let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'change' };
							item.push(eleRule);
						}
						//检查正则是否为null
						if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
							//不为空，将字符串转成正则表达式
							let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'change' }
							item.push(eleRule);
						}
					}
					let name = obj.name;
					_this.fieldRules[name] = item;
				};
			},
			//下拉树
			handleDropdownMultipleTreeCheck() {
				let _this = this;
				//获取所有选中的节点只有全选节点
				let selectedNodes = _this.$refs.categoryTree.getCheckedNodes();
				let lableArr = new Array();//显示选中的值
				let categorys = [];
				selectedNodes.forEach(ele => {
					lableArr.push("【" + ele.title + "】");
					categorys.push(ele.id);
				});
				if (lableArr.length > 0) {
					_this.model.categorys = categorys;
					_this.dropdownMultipleTree.dropdownLable = lableArr.join(',');
				} else {
					_this.model.categorys = [];
					_this.dropdownMultipleTree.dropdownLable = '请选择栏目类别';
				}
			},
			//点击状态按钮
			handleChangeStatus(val) {
				let _this = this;
				_this.model.categorys = [];
				_this.dropdownMultipleTree.dropdownLable = '请选择栏目类别';
			},
			//格式化相册数据
			formatAlbum() {
				let _this = this;
				let albumsArr = [];
				if (_this.model.albums) {
					let albums = _this.model.albums;
					for (let i = 0; i < albums.length; i++) {
						if (albums[i].status === 'success') {
							albumsArr.push(albums[i]);
						}
					}
					_this.model.albums = albumsArr;
				}
			},
			//格式化附件数据
			formatAttach() {
				let _this = this;
				let attachArr = [];
				if (_this.model.attachs) {
					let attachs = _this.model.attachs;
					for (let i = 0; i < attachs.length; i++) {
						if (attachs[i].status === 'success') {
							attachArr.push(attachs[i]);
						}
					}
					_this.model.attachs = attachArr;
				}
			},
		},
		created() {
			//初始化数据
			this.initData();
		}
	}
</script>

<style lang="scss">
</style>